package com.photography.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;

import com.photography.common.Result;
import com.photography.entity.Order;
import com.photography.exception.ErrorCode;
import com.photography.mapper.OrderMapper;
import com.photography.service.AlipayService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class AlipayServiceImpl implements AlipayService {

    private static final Logger logger = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Resource
    private AlipayClient alipayClient;
    
    @Resource
    private OrderMapper orderDao;
    
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Override
    public Result createPayment(Integer orderId) {
        try {
            logger.info("开始创建支付订单，订单ID: {}", orderId);
            
            // 查询订单
            Order order = orderDao.findById(orderId);
            if (order == null) {
                logger.error("订单不存在，订单ID: {}", orderId);
                return Result.error("订单不存在", ErrorCode.ORDER_NOT_EXIST.getCode());
            }
            logger.info("查询到订单信息: {}", order);
            
            // 获取所有相关订单的总金额
            List<Order> relatedOrders = orderDao.findRelatedOrders(order.getUserId());
            if (relatedOrders == null || relatedOrders.isEmpty()) {
                logger.error("未找到相关订单，用户ID: {}", order.getUserId());
                return Result.error("未找到相关订单", ErrorCode.ORDER_NOT_EXIST.getCode());
            }
            logger.info("查询到相关订单数量: {}", relatedOrders.size());
            
            // 计算所有待支付订单的总金额
            BigDecimal totalAmount = relatedOrders.stream()
                .filter(o -> "待支付".equals(o.getOrderStatus()))
                .map(Order::getOrderAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
            logger.info("计算得到的总金额: {}", totalAmount);
            
            // 创建支付请求
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(notifyUrl);
            request.setReturnUrl(returnUrl);
            
            // 构建支付参数，使用总金额
            String bizContent = String.format(
                "{\"out_trade_no\":\"%s\"," +
                "\"total_amount\":\"%.2f\"," +
                "\"subject\":\"摄影订单-%s\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}",
                order.getOrderId(),
                totalAmount,
                order.getOrderId()
            );
            request.setBizContent(bizContent);
            logger.info("构建的支付参数: {}", bizContent);
            
            // 调用支付宝接口
            logger.info("开始调用支付宝接口...");
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            logger.info("支付宝接口调用结果: {}", response.getBody());
            
            if (response.isSuccess()) {
                logger.info("创建支付订单成功");
                return Result.success(response.getBody());
            } else {
                logger.error("创建支付订单失败，错误码: {}, 错误信息: {}", response.getCode(), response.getMsg());
                return Result.error("创建支付订单失败: " + response.getMsg(), ErrorCode.BUSINESS_ERROR.getCode());
            }
        } catch (Exception e) {
            logger.error("创建支付订单异常", e);
            return Result.error("创建支付订单异常: " + e.getMessage(), ErrorCode.SYSTEM_INNER_ERROR.getCode());
        }
    }

    @Override
    @Transactional
    public Result handleNotify(String tradeStatus, String outTradeNo, String tradeNo) {
        try {
            // 查询订单
            Order order = orderDao.findById(Integer.parseInt(outTradeNo));
            if (order == null) {
                return Result.error("订单不存在", ErrorCode.ORDER_NOT_EXIST.getCode());
            }
            
            // 验证支付状态
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                // 更新订单状态
                order.setOrderStatus("已支付");
                orderDao.updateById(order);
                return Result.success();
            } else {
                return Result.error("支付未完成", ErrorCode.BUSINESS_ERROR.getCode());
            }
        } catch (Exception e) {
            return Result.error("处理支付回调异常", ErrorCode.SYSTEM_INNER_ERROR.getCode());
        }
    }

    @Override
    public Result queryPayment(String outTradeNo) {
        try {
            // 创建查询请求
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            String bizContent = String.format(
                "{\"out_trade_no\":\"%s\"}",
                outTradeNo
            );
            request.setBizContent(bizContent);
            
            // 调用支付宝接口
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                return Result.success(response.getTradeStatus());
            } else {
                return Result.error("查询支付结果失败", ErrorCode.BUSINESS_ERROR.getCode());
            }
        } catch (Exception e) {
            return Result.error("查询支付结果异常", ErrorCode.SYSTEM_INNER_ERROR.getCode());
        }
    }
} 